<template>
  <view :data-theme="globPrimary">
    <u-navbar>
      <view class="topic-navbar-collection" @click="changeCollection">
        <u-icon name="star-fill" :color="collected ? '#FF8A52' : '#DCDFE6'" size="40"></u-icon>
      </view>
    </u-navbar>
    <view class="topic-header u-flex">
      <view class="answered" :style="[{ top: answeredTop }]" v-if="hasAnswered">
        <!-- 最后一个显示正确 -->
        <u-image
          width="148rpx"
          height="148rpx"
          src="@/pageFound/static/images/sure.png"
          class="img"
          v-show="
            (type == 0 && hasAnswered == 1 && isRight) ||
            (type == 1 && hasAnswered == 1 && isRight && $u.test.empty(nextTopicId))
          "
        ></u-image>
        <u-image
          width="148rpx"
          height="148rpx"
          src="@/pageFound/static/images/wrong.png"
          class="img"
          v-show="hasAnswered == 1 && !isRight"
        ></u-image>
      </view>
    </view>

    <view class="topic-body" v-for="item in topicList" :key="item.id">
      <practice-question
        :question="item"
        :value="questionValue(item)"
        @change="handleQuestionChange"
        :disabled="hasAnswered == 1"
      ></practice-question>
      <practice-parsing
        :parsing="item"
        v-if="
          (type == 0 && hasAnswered == 1) ||
          (type == 1 && hasAnswered == 1 && !isRight) ||
          (type == 1 && hasAnswered == 1 && $u.test.empty(nextTopicId))
        "
      ></practice-parsing>
    </view>

    <practice-pagination
      :show-prev-button="false"
      :show-next-button="!$u.test.empty(nextTopicId) && type == 1"
      :show-confirm-button="type == 0 || $u.test.empty(nextTopicId)"
      :disabled="disabled"
      @next="handleTopicNext"
      @confirm="handleQuestionAnswer"
    ></practice-pagination>
  </view>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
import practiceQuestion from './components/practice-question.vue'
import practiceParsing from './components/practice-parsing.vue'
import practicePagination from './components/practice-pagination.vue'
export default {
  components: {
    practiceQuestion,
    practiceParsing,
    practicePagination,
  },
  data() {
    return {
      type: 0,
      topicId: 0,
      nextTopicId: 0,
      loading: false,
      examTitle: '', // 考试标题
      examCount: 0, // 试题总数
      topicList: [],
      disabled: false,
    }
  },
  computed: {
    ...mapState({
      topicRulesList: (state) => state.examPractice.topicList,
    }),
    ...mapGetters({
      globPrimary: 'designSetting/getGlobTheme',
      globPrimaryColor: 'designSetting/getGlobThemeColor',
      globNavbarHeight: 'projectSetting/globNavbarHeight',
      globStatusBarHeight: 'projectSetting/globStatusBarHeight',
    }),
    // 收藏状态
    collected() {
      const topic = this.topicList.find((item, index) => item)
      if (this.$u.test.empty(topic)) return 0
      return topic.collected
    },
    // 当前试题是否作答
    hasAnswered() {
      if (this.$u.test.empty(this.topicRulesList)) return 0
      const topic = this.topicRulesList.find((item) => item.topic_id == this.topicId)
      if (this.$u.test.empty(topic) || this.$u.test.empty(topic.has_answered)) {
        return 0
      }
      return topic.has_answered
    },
    // 是否作答正确
    isRight() {
      if (this.$u.test.empty(this.topicRulesList)) return 0
      const topic = this.topicRulesList.find((item) => item.topic_id == this.topicId)
      if (this.$u.test.empty(topic) || this.$u.test.empty(topic.is_right)) {
        return 0
      }
      return topic.is_right
    },
    answeredTop() {
      let top = this.globNavbarHeight + this.globStatusBarHeight + uni.upx2px(16) + 'px'
      return top
    },
  },
  onLoad(option) {
    this.getExamTopic(option.id)
    if (!this.$u.test.empty(option.type)) {
      this.type = option.type
    }
  },
  methods: {
    // 获取试题
    getExamTopic(id) {
      uni.showLoading({
        title: '加载中...',
      })
      this.loading = true
      return new Promise((resolve) => {
        this.$edu.api
          .getWrongTopic({
            record_id: id,
          })
          .then((res) => {
            const { data } = res
            this.disabled = false
            this.topicList = data
            const topic = this.topicList.find((item) => item)
            this.topicId = topic.id
            this.nextTopicId = topic.next_record_id
            // 组装数据
            this.$store.commit('examPractice/init', [
              {
                data: [
                  {
                    topic_id: topic.id,
                    has_answered: 0,
                    is_right: 0,
                  },
                ],
              },
            ])
            this.changeCorrectAnswer()
            setTimeout(() => {
              this.loading = false
              uni.hideLoading()
            }, 500)
            resolve()
          })
          .catch((err) => {
            uni.hideLoading()
          })
      })
    },
    // 当前值
    questionValue(item) {
      const rules = this.topicRulesList.find((item) => item.topic_id == this.topicId)
      let empty = null
      if (this.$edu.test.inArray(item.question_type, [1, 2])) {
        empty = ''
      } else if (this.$edu.test.inArray(item.question_type, [3, 4, 7])) {
        empty = []
      }
      if (this.$u.test.empty(rules) || this.$u.test.empty(rules.current_answer)) {
        return empty
      } else {
        return rules.current_answer
      }
    },
    // 保存正确的答案
    changeCorrectAnswer() {
      let topic = this.topicList.find((item) => item)
      let answer = null
      if (this.$edu.test.inArray(topic.question_type, [1, 2])) {
        // 单选/判断
        let option = topic.options.find((item) => item.is_right)
        if (option) {
          answer = option.id
        }
      } else if (this.$edu.test.inArray(topic.question_type, [3, 4])) {
        // 多选/不定项选择
        let option = topic.options.filter((item) => item.is_right == 1)
        if (!this.$u.test.empty(option)) {
          answer = option.map((item) => item.id)
        }
      } else if (this.$edu.test.inArray(topic.question_type, [7])) {
        // 完型填空
        let option = topic.topics.map((ele) => {
          let options = ele.options.find((item) => item.is_right == 1)
          return options.id
        })
        if (!this.$u.test.empty(option)) {
          answer = option
        }
      }
      this.$store.commit('examPractice/changeCorrectAnswer', {
        id: this.topicId,
        answer: answer,
      })
    },
    // 下一题
    handleTopicNext() {
      if (!this.loading) {
        if (this.hasAnswered) {
          this.$store.commit('examPractice/next')
          this.getExamTopic(this.nextTopicId)
        } else {
          this.handleQuestionAnswer()
          if (this.isRight && this.nextTopicId) {
            this.$store.commit('examPractice/next')
            this.getExamTopic(this.nextTopicId)
          }
        }
      }
    },
    // 选择的答案变化时
    handleQuestionChange(e) {
      if (!this.loading) {
        this.$store.commit('examPractice/changeCurrentAnswer', {
          id: this.topicId,
          answer: e,
        })
      }
    },
    // 提交单项答案时
    handleQuestionAnswer() {
      this.disabled = true
      if (!this.loading && !this.hasAnswered) {
        const rules = this.topicRulesList.find((item) => item.topic_id == this.topicId)
        const topic = this.topicList.find((item) => item)
        let is_right = 0
        if (this.$edu.test.inArray(topic.question_type, [1, 2])) {
          // 单选
          if (rules.correct_answer && rules.current_answer) {
            is_right = rules.current_answer == rules.correct_answer ? 1 : 0
          }
        } else {
          // 多选/数组
          if (rules.correct_answer && rules.current_answer) {
            if (rules.correct_answer.length == rules.current_answer.length) {
              let num = rules.correct_answer.every((item) => rules.current_answer.includes(item))
              is_right = num ? 1 : 0
            } else {
              is_right = 0
            }
          }
        }
        this.$store.commit('examPractice/submitCurrentAnswer', {
          id: topic.id,
          is_right: is_right,
        })
        this.$edu.api.referWrongTopic({
          topic_level: 1,
          topic_id: topic.id,
          is_right: is_right,
        })
      }
    },
    // 收藏
    changeCollection() {
      if (!this.loading) {
        let status = this.collected == 1 ? 0 : 1
        this.$edu.api
          .getTopicCollect({
            topic_id: this.topicId.toString(),
            status: status,
          })
          .then((res) => {
            this.$u.toast(res.data)
            let topic = this.topicList.find((item) => item)
            topic.collected = status
          })
      }
    },
  },
  destroyed() {
    this.$store.commit('examPractice/init')
  },
}
</script>
<style lang="scss">
page {
  background-color: #ffffff;
}
</style>
<style lang="scss" scoped>
.topic-navbar-collection {
  padding: 10px 20rpx;
  margin-left: auto;
}
.topic-header {
  margin-top: 30rpx;
  position: relative;
  .answered {
    position: fixed;
    right: 8rpx;
    z-index: 99;
  }
}
.topic-body {
  padding: 0 30rpx;
  margin-bottom: 30rpx;
}
</style>
